package com.LeeCode;

import java.util.*;

/**
 * 二叉树的锯齿形层序遍历
 */

public class Code103 {
    public static void main(String[] args) {
        Integer[] arr = {3, 9, 20, null, null, 15, 7};
        TreeNode root = Utils.buildTree(arr);
        System.out.println(new Code103().zigzagLevelOrder(root));
    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        boolean reverse = false;
        while (!queue.isEmpty()) {
            int currentLevelSize = queue.size();
            List<Integer> level = new ArrayList<>(currentLevelSize);
            for (int i = 1; i <= currentLevelSize; ++i) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            if (reverse) {
                Collections.reverse(level);
            }
            reverse = !reverse;
            ans.add(level);
        }

        return ans;
    }
}
